package versionhelper

import (
    "errors"
    "strconv"
    "strings"
)


const (
    VERSION_EQUAL = 0
    VERSION_GREATER_THAN  = 1
    VERSION_LESS_THAN = 2
)

// 客户端版本比较
func VersionCompare(v1, v2, operator string) (ok bool, err error) {
    ok = false
    var result int

    if result, err = compare(v1, v2); err != nil {
        return
    }

    switch operator {
    case "==":
        if result == VERSION_EQUAL {
            ok = true
        }
    case "<":
        if result == VERSION_LESS_THAN {
            ok = true
        }
    case ">":
        if result == VERSION_GREATER_THAN {
            ok = true
        }
    case "<=":
        if result == VERSION_EQUAL || result == VERSION_LESS_THAN {
            ok = true
        }
    case ">=":
        if result == VERSION_EQUAL || result == VERSION_GREATER_THAN{
            ok = true
        }
    default:
        err = errors.New("非法比较符")
        ok = false
    }
    return
}

// 替换版本号中的无效字符
var replaceMap = map[string]string{"V": "", "v": "", "-": "."}

func preprocessVersion(ver string) (intVerList []int, err error) {
    for raw, replace := range replaceMap {
        //if strings.Contains(ver, raw) {
            ver = strings.Replace(ver, raw, replace, -1)
        //}
    }

    strVerList := strings.Split(ver, ".")
    intVerList = make([]int, 0)
    for _, strVer := range strVerList {
        var intVer int

        strVer = strings.TrimSpace(strVer)
        if intVer, err = strconv.Atoi(strVer); err != nil {
            return
        }
        intVerList = append(intVerList, intVer)
    }
    return
}

func compare(v1, v2 string) (result int, err error) {
    var ver1, ver2 []int

    if ver1, err = preprocessVersion(v1); err != nil {
        return
    }
    if ver2, err = preprocessVersion(v2); err != nil {
        return
    }

    minLen := len(ver1)
    if len(ver2) < minLen {
        minLen = len(ver2)
    }

    for i := 0; i < minLen; i++ {
        if ver1[i] < ver2[i] {
            return  VERSION_LESS_THAN, nil
        } else if ver1[i] > ver2[i] {
            return VERSION_GREATER_THAN, nil
        }
    }

    if len(ver1) < len(ver2) {
        result = VERSION_LESS_THAN
    } else if len(ver1) > len(ver2) {
        result = VERSION_GREATER_THAN
    } else {
        result = VERSION_EQUAL
    }
    return
}

